-- qq 微信 好友 等相关 数据
local DataModel = import(".DataModel")
local MsdkData = class("MsdkData", DataModel)
local Friend = import(".Friend")

function MsdkData:ctor(  )
	-- body
	MsdkData.super.ctor(self)
	self._vip = Enums.MSDK_QQ_VIP.VIP_NONE
	self._wakeUpFrom = Enums.WAKE_UP.NONE
	self._isLoginAwardTaken = false
	self._joinedGroupState = Enums.MsdkGroupJoinState.Unknown
end


function MsdkData:_updateMsdkInfo(ret)
	self._vip = ret.vip
	
	self._wakeUpFrom = ret.wakeUpFrom
	self._isLoginAwardTaken = ret.isLoginAwardTaken
	self:dispatchChange("init")
end

function MsdkData:_updateMsdkFriend(ret)
	local friends = app.channelAPI:queryGameFriendsInfo()
	if not self._msdkFriend then
		local msdkFriend = {}
		if friends then
			for k, v in pairs(friends) do
				msdkFriend[v.openId] = v
			end
		end
		self._msdkFriend = msdkFriend
	end
	self._msdkFriendGameUser = {}
	for k ,v in pairs(ret.user) do
		local friend = Friend.new(v, Enums.FriendType.msdk)
		table.insert(self._msdkFriendGameUser, friend)
		if friend.openId then
			local temp = self._msdkFriend[friend.openId]
			if temp then
				friend:setHeadUrl(temp.pictureLarge, app.channelAPI:getHeadCachePathByOpenId(friend.openId))
				friend:setMsdkNickname(temp.nickName)
			end
		end
	end

	table.sort(self._msdkFriendGameUser, function(a, b)
		return a.info.level > b.info.level
	end)

	for k ,v in ipairs(self._msdkFriendGameUser) do
		v:setRank(k)
	end

	self:dispatchChange("friend")
end

function MsdkData:getMsdkFriendGameUser(isForce)
	if self._msdkFriendGameUser then
		if isForce then
			self:requestUserInfoByOpenIds()
		end
		return self._msdkFriendGameUser
	end
	self:requestUserInfoByOpenIds()
	return  {}
end


function MsdkData:setLoginAward(trueOrFalse)
	self._isLoginAwardTaken = trueOrFalse
	self:dispatchChange("loginAward")
end


function MsdkData:isFunctionEnable()
	if not QQ_WX_FUNCTION_OPEN then
		return false
	end
	if app.channelAPI:isReview() then
		return false
	end
	if app:getPublisher() ~= Enums.Publisher.tencent then
		return false
	end


	return true
end


function MsdkData:isQQPlatform(isCheckChannel)
	if not self:isFunctionEnable() then
		return false
	end
	if isCheckChannel and self:isNotTencentChannel() then
		return false
	end
	return app.channelAPI:getWGPlatform() == Enums.MSDK_PLATFORM.QQ
end

function MsdkData:isWXPlatform(isCheckChannel)
	if not self:isFunctionEnable() then
		return false
	end

	if isCheckChannel and self:isNotTencentChannel() then
		return false
	end

	return app.channelAPI:getWGPlatform() == Enums.MSDK_PLATFORM.WX
end

function MsdkData:isWakeUpFromQQGame(wakeUpFrom)
	if not self:isFunctionEnable() then
		return false
	end
	if not wakeUpFrom then
		return false
	end

	if self:isNotTencentChannel() then
		return false
	end

	return app.channelAPI:getWGPlatform() == Enums.MSDK_PLATFORM.QQ and wakeUpFrom == Enums.WAKE_UP.QQGAME
end

function MsdkData:isQQVip(vip)
	if not self:isFunctionEnable() then
		return false
	end

	if not vip then
		return false
	end

	if self:isNotTencentChannel() then
		return false
	end

	return app.channelAPI:getWGPlatform() == Enums.MSDK_PLATFORM.QQ and vip ~= Enums.MSDK_QQ_VIP.VIP_NONE
end

function MsdkData:isWakeUpFromWXGame(wakeUpFrom)
	if not self:isFunctionEnable() then
		return false
	end
	if not wakeUpFrom then
		return false
	end

	if self:isNotTencentChannel() then
		return false
	end

	return app.channelAPI:getWGPlatform() == Enums.MSDK_PLATFORM.WX and wakeUpFrom == Enums.WAKE_UP.WXGAME
end


function MsdkData:isMyWakeUpFromWXGame()
	return self:isWakeUpFromWXGame(self._wakeUpFrom)
end

function MsdkData:isMyWakeUpFromQQGame()
	return self:isWakeUpFromQQGame(self._wakeUpFrom)
end


function MsdkData:getWakeUpFrom()
	return self._wakeUpFrom
end

function MsdkData:isVip()
	return self:isQQVip(self._vip)
end

function MsdkData:getVip()
	return self._vip
end

function MsdkData:getMsdkPlatfrom()
	return app.channelAPI:getWGPlatform()
end

function MsdkData:getMyHeadUrlAndCachePath()
	if not self:isFunctionEnable() then
		return
	end
	local myInfo = app.channelAPI:queryMyInfo()
	if myInfo then
		return myInfo.pictureLarge,  app.channelAPI:getHeadCachePathByOpenId(app.channelAPI:getOpenId())
	end
	-- return "http://q.qlogo.cn/qqapp/1105873472/F59CCE6DF0017B7FAFA05AC09BE14D35/100", app:getStorePath() .. "/head/"..app.channelAPI:getOpenId()
end


function MsdkData:getMyNickname()
	if not self:isFunctionEnable() then
		return ""
	end
	local myInfo = app.channelAPI:queryMyInfo()
	if myInfo then
		return myInfo.nickName
	end
	return ""
end


function MsdkData:requestMsdkBusiness()
	if not self:isFunctionEnable() then
		return 
	end
	local wakeUp = app.channelAPI:getWakeUpFrom()
	print("xxxxxxxxxxxxxxxxxxx requestMsdkBusiness===========2222222", wakeUp)
	app.session:request("tencent.C2S_MsdkBusiness",{wakeUpFrom = wakeUp}, function(ret, err)
		print("xxxxxxxxxxxxxxxxxxx ===========333333", ret.vip, ret.wakeUpFrom)
        self:_updateMsdkInfo(ret)
    end)
end

function MsdkData:requestGetMsdkLoginAward()
	if self._wakeUpFrom == Enums.WAKE_UP.NONE then
		return
	end
	if not self:isFunctionEnable() then
		return 
	end
	if self._isLoginAwardTaken then
		return
	end
	app.session:request("tencent.C2S_GetMsdkLoginAward",{}, function(ret, err)
		if ret.ok then
			local platForm = app.channelAPI:getWGPlatform()
			if platForm == Enums.MSDK_PLATFORM.QQ then
				display.pushToast(L("获取QQ游戏中心启动特权奖励")) --@ignore
			elseif platForm == Enums.MSDK_PLATFORM.WX then
				display.pushToast(L("获取WX游戏中心启动特权奖励")) --@ignore
			end
		end
		self:setLoginAward(ret.ok)
    end)
end

function MsdkData:requestUserInfoByOpenIds()
	if not self:isFunctionEnable() then
		return
	end

	local friends = app.channelAPI:queryGameFriendsInfo()
	if not friends then
		return
	end
	local openIds = {}
	for k, v in pairs(friends) do
		table.insert(openIds, v.openId)
	end
	-- table.insert(openIds, app.channelAPI:getOpenId())

	app.session:request("tencent.C2S_GetGameUserByOpenIds",{openIds = openIds}, function(ret, err)
        self:_updateMsdkFriend(ret)
    end)
end

function MsdkData:qqVipClickTip()
	display.pushToast(L("FriendQQVipStr"))
end

function MsdkData:qqGameCenterClickTip()
	display.pushToast(L("FriendQQGameCenterStr"))
end


function MsdkData:wxGameCenterClickTip()
	display.pushToast(L("FriendWXGameCenterStr"))
end



function MsdkData:qqGameWakeUpClick()
	if not self:isFunctionEnable() then
		return
	end
	if not cc.isDead(self._gameCenterPop) then
		return
	end
	local QQGameCenterPop = require("app.msdk.views.QQGameCenterPop")
    local view = QQGameCenterPop.new(nil, app.channelAPI:getWGPlatform())
    view:onCloseView(function(sender)
		UIHandler:removePopupUiByKey(sender:getViewName())
		self._gameCenterPop = nil
    end)
    UIHandler:addPopupUi(view, view:getViewName())
	view:show()
	self._gameCenterPop = view
end

function MsdkData:qqVipClick()
	if not self:isFunctionEnable() then
		return
	end
	local pfKey = app.channelAPI:getPfKey()
	local zoneId = self:getZoneId()
	local roleId = tostring(UD.player.uid)
	local url =  "https://mq.vip.qq.com/m/game/vipembed?sRoleId="..roleId.."&sPartition="..zoneId.."&sPfkey="..pfKey
	app.channelAPI:openURL(url)
end


function MsdkData:wxGameWakeUpClick()
	if not self:isFunctionEnable() then
		return
	end
	if not cc.isDead(self._gameCenterPop) then
		return
	end
	local WXGameCenterPop = require("app.msdk.views.WXGameCenterPop")
    local view = WXGameCenterPop.new(nil, app.channelAPI:getWGPlatform())
    view:onCloseView(function(sender)
		UIHandler:removePopupUiByKey(sender:getViewName())
		self._gameCenterPop = nil
    end)
    UIHandler:addPopupUi(view, view:getViewName())
	view:show()
	self._gameCenterPop = view
end

function MsdkData:shareToFriend(openId, title, desc, ext)
	if not self:isFunctionEnable() then
		return
	end
	if not openId then
		return
	end
	if not title then
		title = "无尽" --@ignore
	end
	if not desc then
		desc = "测试交互" --@ignore
	end

	if not ext then
		ext = "111"
	end
	print("======.>>>  shareToFriend")
	app.channelAPI:shareToFriend(nil, openId, title, desc, ext)
end

function MsdkData:inviteFriend()
	if not self:isFunctionEnable() then
		return
	end
	app.channelAPI:inviteFriend()
end

-- 公会绑群的
function MsdkData:_runWithCheckGuidInfo(func)
	local newguildModel = app:getInst("NewguildModel")
    if newguildModel then
		local myGuild = newguildModel:getMyGuildInfo()
		if myGuild then
			func(myGuild, newguildModel)
			return true
		end
	end
end

function MsdkData:_genWXGroupId()
	if not self._wxGroupId then
		self:_runWithCheckGuidInfo(function(myGuild, guildModel)
			local serverId = tostring(app.session:getZoneId()) or ""
			local guildId = myGuild:getGuildId() or ""
			self._wxGroupId = "WX_"..serverId..guildId
		end)
	end
	return self._wxGroupId
end


function MsdkData:getMsdkGroupId()
	local id = nil
	self:_runWithCheckGuidInfo(function(myGuild, guildModel)
		id = myGuild:getMsdkGroupId()
	end)
	return id
end

-- 获取 公会群binged状态
function MsdkData:getGroupBindedState()
	local msdkGroupId = self:getMsdkGroupId()
	return msdkGroupId ~= "" and msdkGroupId ~= nil
end

-- 获取 公会群加入状态
function MsdkData:getGroupJoinedState(isForce)
	if isForce or self._joinedGroupState == Enums.MsdkGroupJoinState.Unknown then
		self:queryGroupInfo()
	end
	return self._joinedGroupState
end

function MsdkData:_setJoinedState(state, notDispatch)
	if self._joinedGroupState == state then
		return
	end
	self._joinedGroupState = state
	if not notDispatch then
		EM:notify(ViewEvent.Msdk_GuildBindedChange)
	end
end

function MsdkData:recheckJoinMsdkGroupState()
	if not self:isFunctionEnable() then
		return
	end

	-- 先检查一下 群是否已经创建  在检查 和群的关系
	-- 在拉起微信的情况下， 点击留在微信  会导致 接收不到回调 导致绑群状态没有记录到服务器不对
	self:queryGroupIsCreate(function()
		self:queryGroupInfo(0)
	end, 15)
end

-- 查询 公会成员和群关系
function MsdkData:queryGroupInfo(intervalTime)
	if not self:isFunctionEnable() then
		return
	end

	if not self:getGroupBindedState()  then
		self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded)
		return 
	end

	local msdkGroupId = self:getMsdkGroupId()

	if not intervalTime then
		intervalTime = 5
	end

	local nowTime = app.session:getServerTime()

	if self._queryGroupInfoTime then
		if nowTime - self._queryGroupInfoTime <= intervalTime then
			return
		end
	end
	self._queryGroupInfoTime = nowTime

	local wgPlatform = app.channelAPI:getWGPlatform()
	if Enums.MSDK_PLATFORM.QQ == wgPlatform then
		app.channelAPI:queryQQGroupInfo(msdkGroupId, function(ret)
			if ret.flag == 0 then
				local relation = ret.relation;
				print("==========>>> relation: ", relation)
				--用户与群的关系，1:群主，2:管理员，3:普通成员，4:非成员 ,-1 查询错误
				if relation == 1 or relation == 2 or relation == 3 then
					self:_setJoinedState(Enums.MsdkGroupJoinState.Joined)
				elseif relation == 4 then
					self:_setJoinedState(Enums.MsdkGroupJoinState.Unjoin)
				else
					-- 检查 binded状态
					self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded)
				end
			else
				self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded)
				-- print("==========>>> errcode: ", ret.errorCode, ret.desc)
			end
		end)
	elseif Enums.MSDK_PLATFORM.WX == wgPlatform then
		local openId = app.channelAPI:getOpenId()
		app.channelAPI:queryWXGroupInfo(msdkGroupId, openId, function(ret)
			if ret.flag == 0 then
				local openIdList = ret.openIdList or ""
				local openIdListArr = string.split( openIdList,  ",")
				local isFind = false
				for k, v in pairs(openIdListArr) do
					if v == openId then
						isFind = true
						self:_setJoinedState(Enums.MsdkGroupJoinState.Joined)
						break
					end
				end
				if not isFind then
					self:_setJoinedState(Enums.MsdkGroupJoinState.Unjoin)
				end
			else
				print("==========>>> errcode: ", ret.errorCode, ret.desc)
				if -10007 == ret.errorCode then
					-- 群id 不存在
					self:_runWithCheckGuidInfo(function(myGuild)
						myGuild:setMsdkGroupId("")
						self:C2S_UnBindQQGroup()
						self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded)
					end)
				else
					self:_setJoinedState(Enums.MsdkGroupJoinState.Unjoin)
				end
			end
		end)
	end
end


function MsdkData:getZoneId()
	-- return "0"
	return tostring(app.session:getZoneId())
end


-- 检查公会群是否已创建 
function MsdkData:queryGroupIsCreate(callback, intervalTime)
	if not self:isFunctionEnable() then
		return
	end

	if not intervalTime then
		intervalTime = 5
	end
	local nowTime = app.session:getServerTime()
	if self._queryGroupIsCreateTime then
		if nowTime - self._queryGroupIsCreateTime <= intervalTime then
			return
		end
	end
	self._queryGroupIsCreateTime = nowTime
	-- 这里 也把这个值赋值上 避免 queryGroupInfo 调用多次
	self._queryGroupInfoTime = nowTime 
	

	local wgPlatform = app.channelAPI:getWGPlatform()
	if Enums.MSDK_PLATFORM.QQ == wgPlatform then
		self:_runWithCheckGuidInfo(function(myGuild, guildModel)
			local getGroupCodeGuildInfo = {}
			getGroupCodeGuildInfo.guildId = myGuild:getGuildId()
			getGroupCodeGuildInfo.zoneId = self:getZoneId()
			getGroupCodeGuildInfo.partition = tostring(app.session:getZoneId())
			getGroupCodeGuildInfo.type = "0"
			getGroupCodeGuildInfo.areaId = app.channelAPI:getArea()
			local msdkGroupId = myGuild:getMsdkGroupId()
			app.channelAPI:getQQGroupCode(getGroupCodeGuildInfo, function(getGroupRet)
				if getGroupRet.flag == 0 and getGroupRet.qqGroups and #getGroupRet.qqGroups >= 1 then
						local qqGroupInfo = getGroupRet.qqGroups[1]
						local qqGroupId = qqGroupInfo[1]
						local qqGroupName = qqGroupInfo[2]
						if qqGroupId and qqGroupId ~= "" then
							-- 查询到当前有公会群
							if msdkGroupId and msdkGroupId ~= "" then
								if msdkGroupId ~= qqGroupId then
									-- 当前 服务器后端已保存了这个值， 但是不对 理论上不存在该情况
									release_print("msdkGroupId not equal msdkGroupId")
								end
							else
								-- 如果 当前没有记录 是否已绑定群的话
								myGuild:setMsdkGroupId(qqGroupId)
								self:C2S_BindQQGroup(qqGroupId, true)
							end
						else
							if msdkGroupId and msdkGroupId ~= "" then
								myGuild:setMsdkGroupId("")
								self:C2S_UnBindQQGroup(true)
							end
						end
				else
					-- 没查询到 公会群 直接做解绑操作
					if msdkGroupId and msdkGroupId ~= "" then
						myGuild:setMsdkGroupId("")
						self:C2S_UnBindQQGroup(true)
					end
				end
				-- 查询 成员和公会关系
				if callback then
					callback()
				end
			end)
		end)
	elseif Enums.MSDK_PLATFORM.WX == wgPlatform then
		local groupId = self:_genWXGroupId()
		if not groupId then
			return
		end
		self:_runWithCheckGuidInfo(function(myGuild, guildModel)
			app.channelAPI:queryWXGroupStatus(groupId, 0, function(ret)
				local guildGroupId = myGuild:getMsdkGroupId()
				if ret.flag == 0 then
					if ret.status == 1 then
						if guildGroupId == groupId then
							print("===========>> already binded ")
						else
							myGuild:setMsdkGroupId(groupId)
							self:C2S_BindQQGroup(groupId)
							EM:notify(ViewEvent.Msdk_GuildBindedChange)
						end
					else
						if guildGroupId and guildGroupId ~= "" then
							myGuild:setMsdkGroupId("")
							self:C2S_UnBindQQGroup()
							EM:notify(ViewEvent.Msdk_GuildBindedChange)
						end
					end
				else
					self:_handlerWxGroupErrCode(ret)
				end
				-- 查询 成员和公会关系
				if callback then
					callback()
				end
			end)
		end)
	end
end


function MsdkData:createGroup()
	if not self:isFunctionEnable() then
		return
	end
	local wgPlatform = app.channelAPI:getWGPlatform()
	if Enums.MSDK_PLATFORM.QQ == wgPlatform then
		self:_runWithCheckGuidInfo(function(myGuild, guildModel)
			local getGroupCodeGuildInfo = {}
			getGroupCodeGuildInfo.guildId = myGuild:getGuildId()
			getGroupCodeGuildInfo.zoneId = self:getZoneId()
			getGroupCodeGuildInfo.partition = tostring(app.session:getZoneId())
			getGroupCodeGuildInfo.type = "0"
			getGroupCodeGuildInfo.areaId = app.channelAPI:getArea()
			-- 判断公会是否绑群
			app.channelAPI:getQQGroupCode(getGroupCodeGuildInfo, function(getGroupRet)
				if getGroupRet.flag == 0 and getGroupRet.qqGroups and #getGroupRet.qqGroups >= 1 and getGroupRet.qqGroups[1][1] ~= "" then
					local qqGroupInfo = getGroupRet.qqGroups[1]
					local qqGroupId = qqGroupInfo[1]
					local qqGroupName = qqGroupInfo[2]
					self:_setJoinedState(Enums.MsdkGroupJoinState.Joined, true)
					myGuild:setMsdkGroupId(qqGroupId)
					self:C2S_BindQQGroup(qqGroupId)
					EM:notify(ViewEvent.Msdk_GuildBindedChange)
					display.pushToast(L("QQGroupBindedSuccess"))
					app.channelAPI:queryQQGroupInfo(qqGroupId, function(qGroupret)
							if qGroupret.flag == 0 then
								local relation = qGroupret.relation;
								print("==========>>> relation: ", relation)
								--用户与群的关系，1:群主，2:管理员，3:普通成员，4:非成员 ,-1 查询错误
								if relation == 1 or relation == 2 or relation == 3 then
									self:_setJoinedState(Enums.MsdkGroupJoinState.Joined)
								elseif relation == 4 then
									self:_setJoinedState(Enums.MsdkGroupJoinState.Unjoin)
								else
									-- 检查 binded状态
									self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded)
								end
							else
								self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded)
								print("==========>>> errcode: ", qGroupret.errorCode, qGroupret.desc)
							end
					end)
				else
					local createGuildInfo = {}
					createGuildInfo.guildId = myGuild:getGuildId()
					createGuildInfo.guildName = myGuild:getGuildName()
					createGuildInfo.zoneId = self:getZoneId()
					createGuildInfo.partition = tostring(app.session:getZoneId())
					createGuildInfo.roleId = tostring(UD.player.uid)
					createGuildInfo.type = "0"
					createGuildInfo.areaId = app.channelAPI:getArea()
					app.channelAPI:createQQGroup(createGuildInfo, function(createRet)
						if createRet.flag == 0 and createRet.qqGroups and #createRet.qqGroups >= 1 then
							local qqGroupInfo = createRet.qqGroups[1]
							local qqGroupId = qqGroupInfo[1]
							local qqGroupName = qqGroupInfo[2]
							-- 校验 是否绑定成功
							app.channelAPI:queryQQGroupInfo(qqGroupId, function(qGroupret)
								if qGroupret.flag == 0 then
									local relation = qGroupret.relation;
									print("==========>>> relation: ", relation)
									--用户与群的关系，1:群主，2:管理员，3:普通成员，4:非成员 ,-1 查询错误
									if relation == 1 or relation == 2 or relation == 3 then
										self:_setJoinedState(Enums.MsdkGroupJoinState.Joined, true)
										myGuild:setMsdkGroupId(qqGroupId)
										self:C2S_BindQQGroup(qqGroupId)
										display.pushToast(L("QQGroupBindedSuccess"))
										EM:notify(ViewEvent.Msdk_GuildBindedChange)
									elseif relation == 4 then
										self:_setJoinedState(Enums.MsdkGroupJoinState.Unjoin)
									else
										-- 检查 binded状态
										self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded)
									end
								else
									self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded)
									print("==========>>> errcode: ", qGroupret.errorCode, qGroupret.desc)
								end
							end)
						else
							if createRet.errorCode == 221011 then
								display.pushToast(L("QQGroupError221011"))
							end
						end
					end)
				end
			end)
		end)
	elseif Enums.MSDK_PLATFORM.WX == wgPlatform then
		local groupId = self:_genWXGroupId()
		if not groupId then
			return
		end
		self:_runWithCheckGuidInfo(function(myGuild, guildModel)
			local guildName = myGuild:getGuildName()
			local name = UD.player.name or ""
			app.channelAPI:createWXGroup(groupId, guildName, name, function(ret)
				if ret.flag == 0 then
					myGuild:setMsdkGroupId(groupId)
					self:C2S_BindQQGroup(groupId)
					self:_setJoinedState(Enums.MsdkGroupJoinState.Joined, true)
					EM:notify(ViewEvent.Msdk_GuildBindedChange)
					display.pushToast(L("WXGroupBindedSuccess"))
				else
					print("==========>>> errcode: ", ret.errorCode, ret.desc)
					self:_handlerWxGroupErrCode(ret)
				end
			end)
		end)
	end
end


function MsdkData:joinGroup()
	if not self:isFunctionEnable() then
		return
	end
	local msdkGroupId = self:getMsdkGroupId()
	if not msdkGroupId or msdkGroupId == "" then
		return
	end
	local wgPlatform = app.channelAPI:getWGPlatform()
	if Enums.MSDK_PLATFORM.QQ == wgPlatform then
		self:_runWithCheckGuidInfo(function(myGuild, guildModel)
			local guildInfo = {}
			guildInfo.guildId = myGuild:getGuildId()
			guildInfo.zoneId = self:getZoneId()
			guildInfo.partition = tostring(app.session:getZoneId())
			guildInfo.roleId = tostring(UD.player.uid)
			guildInfo.type = "0"
			guildInfo.areaId = app.channelAPI:getArea()
			app.channelAPI:joinQQGroup(guildInfo, msdkGroupId, function(ret)
				if ret.flag == 0 then
					self:_setJoinedState(Enums.MsdkGroupJoinState.Joined)
					display.pushToast(L("JoinedGroupSuccess"))
				else
					if ret.errorCode == 221002 then
						-- 没有绑定 qq群， 可能被解散了
						myGuild:setMsdkGroupId("")
						self:C2S_UnBindQQGroup()
						self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded)
					else
						self:_setJoinedState(Enums.MsdkGroupJoinState.Unjoin)
					end
				end

			end)
		end)
	elseif Enums.MSDK_PLATFORM.WX == wgPlatform then
		local name = tostring(UD.player.name)
		app.channelAPI:joinWXGroup(msdkGroupId, name, function(ret)
			if ret.flag == 0 then
				self:_setJoinedState(Enums.MsdkGroupJoinState.Joined)
				display.pushToast(L("JoinedGroupSuccess"))
			else
				self:_handlerWxGroupErrCode(ret)
			end
		end)
	end
end

function MsdkData:unbindGroup()
	if not self:isFunctionEnable() then
		return
	end
	local msdkGroupId = self:getMsdkGroupId()
	if not msdkGroupId or msdkGroupId == "" then
		return
	end

	local wgPlatform = app.channelAPI:getWGPlatform()
	if Enums.MSDK_PLATFORM.QQ == wgPlatform then
		self:_runWithCheckGuidInfo(function(myGuild, guildModel)
			local guildInfo = {}
			guildInfo.guildId = myGuild:getGuildId()
			guildInfo.guildName = myGuild:getGuildName()
			guildInfo.zoneId = self:getZoneId()
			guildInfo.partition = tostring(app.session:getZoneId())
			guildInfo.roleId = tostring(UD.player.uid)
			guildInfo.type = "0"
			guildInfo.areaId = app.channelAPI:getArea()
			
			app.channelAPI:unbindQQGroup(guildInfo, function(ret)
				if ret.flag == 0 or ret.errorCode == 221002 then
					myGuild:setMsdkGroupId("")
					self:C2S_UnBindQQGroup()
					self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded)
					display.pushToast(L("QQGroupUnBindSuccess"))
				else
					if ret.errorCode == 221005 then
						display.pushToast(L("QQGroupUnBindError221005"))
					end
					print("==========>>> errcode: ", ret.errorCode, ret.desc)
				end
			end)
		end)
	elseif Enums.MSDK_PLATFORM.WX == wgPlatform then
		self:_runWithCheckGuidInfo(function(myGuild, guildModel)
			app.channelAPI:unbindWXGroup(msdkGroupId, function(ret)
				if ret.flag == 0 then
					myGuild:setMsdkGroupId("")
					display.pushToast(L("WXGroupUnBindSuccess"))
					self:C2S_UnBindQQGroup()
					self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded)
				else
					self:_handlerWxGroupErrCode(ret)
				end
			end)
		end)
	end
end

function MsdkData:_handlerWxGroupErrCode(ret)
	local code  = ret.errorCode 
	if code == -10007 or code == 2013 then
		-- 群不存在
		self:_runWithCheckGuidInfo(function(myGuild)
			local msdkGroupId = myGuild:getMsdkGroupId()
			if msdkGroupId and msdkGroupId ~= "" then
				myGuild:setMsdkGroupId("")
				self:C2S_UnBindQQGroup()
			end
			self:_setJoinedState(Enums.MsdkGroupJoinState.NotBinded, true)
			EM:notify(ViewEvent.Msdk_GuildBindedChange)
		end)
	elseif code == 2014 then
		display.pushToast(L("WXGroupError2014"))
	elseif code == 2012 then
		display.pushToast(L("WXGroupError2012"))
	elseif code == 2011 then
		display.pushToast(L("WXGroupError2011"))
		self:_runWithCheckGuidInfo(function(myGuild)
			local groupId = self:_genWXGroupId()
			myGuild:setMsdkGroupId(groupId)
			self:C2S_BindQQGroup(groupId)
			EM:notify(ViewEvent.Msdk_GuildBindedChange)
		end)
	elseif code == 2002 then

	elseif code == 2000 then
		display.pushToast(L("tips_3000146"))
	elseif code == 2015 then
		display.pushToast(L("WXGroupError2015"))
	else
		-- display.pushToast("errorCode:"..(code or "nil"))
	end
end

function MsdkData:remindCreateGroup()
	-- local wgPlatform = app.channelAPI:getWGPlatform()
	-- if Enums.MSDK_PLATFORM.QQ == wgPlatform then
		-- self:_runWithCheckGuidInfo(function(myGuild, guildModel)

		-- 	local leader = guildModel:getGuildLeader()
		-- 	if not leader then
		-- 		print("=====>>>> not get leader")
		-- 		return
		-- 	end

		-- 	local guildInfo = {}
		-- 	guildInfo.guildId = myGuild:getGuildId()
		-- 	guildInfo.zoneId = tostring(app.session:getZoneId())
		-- 	guildInfo.roleId = tostring(UD.player.uid)
		-- 	guildInfo.type = "0"
		-- 	guildInfo.areaId = "1"

		-- 	-- guildInfo.leaderOpenid = leader:getMemberId()
		-- 	guildInfo.leaderRoleId = leader:getMemberId()
		


		-- 	app.channelAPI:remindGuildLeader(guildInfo, function(ret)
		-- 		if ret.flag == 0 then
		-- 			myGuild:setMsdkGroupId(nil)
		-- 			self:C2S_UnBindQQGroup()
		-- 		else
		-- 			print("==========>>> errcode: ", ret.errorCode, ret.desc)
		-- 		end
		-- 	end)
		-- end)
	-- end
end

-- 非腾讯渠道
function MsdkData:isNotTencentChannel()
	local isChannelIdFromTencent = app.channelAPI:isChannelIdFromTencent()
	return not isChannelIdFromTencent
end


function MsdkData:isEnableShowQQGameCenterView()
	if not self:isFunctionEnable() then
		return false
	end
	
	if app.channelAPI:getWGPlatform() ~= Enums.MSDK_PLATFORM.QQ then
		return false
	end

	if self:isNotTencentChannel() then
		return false
	end
	return true
end

function MsdkData:isEnableShowWXGameCenterView()
	if not self:isFunctionEnable() then
		return false
	end
	
	if app.channelAPI:getWGPlatform() ~= Enums.MSDK_PLATFORM.WX then
		return false
	end

	if self:isNotTencentChannel() then
		return false
	end
	return true
end

function MsdkData:isEnableShowBonus()
	if not self:isFunctionEnable() then
		return false
	end

	if self:isNotTencentChannel() then
		return false
	end
	return true
end

function MsdkData:C2S_BindQQGroup(id, isNeedReset)
	app.session:request("pb_guild.C2S_BindQQGroup",{msdkGroupId = id},function(msg)
			-- isNeedReset
			-- 之前在处理通知服务器绑群的接口里面  由于 打开公会的时候 会请求我的公会信息
			-- 这时 queryGroupIsCreate 如果修正了绑群状态，由于 S2C_MyGuildInfo 会把 msdkGroupId 重置回去
			-- 这里加这段代码 来修复这个问题
			-- todo 这个结构不好 理论上应该 服务器回包之后再改客户端的值， 但是之前做的时候 考虑这个值 完全由客户端决定 服务器只是一个保存功能 所以就...
			-- 基于目前 绑群其他方面 还算稳定 先已风险最小方式修复
			if isNeedReset then
				self:_runWithCheckGuidInfo(function(myGuild, guildModel)
					myGuild:setMsdkGroupId(id)
					EM:notify(ViewEvent.Msdk_GuildBindedChange)
				end)
			end

	end)
end

function MsdkData:C2S_UnBindQQGroup(isNeedReset)
	app.session:request("pb_guild.C2S_UnBindQQGroup",{},function(msg)
		if isNeedReset then
			self:_runWithCheckGuidInfo(function(myGuild, guildModel)
				myGuild:setMsdkGroupId("")
				EM:notify(ViewEvent.Msdk_GuildBindedChange)
			end)
		end
	end)
end



return MsdkData